package com.aps.apspda.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.aps.apspda.R;
import com.aps.apspda.adapter.EqpThingListAdapter;
import com.aps.apspda.adapter.InputDataListAdapter;
import com.aps.apspda.adapter.MessageListAdapter;
import com.aps.apspda.adapter.ThingListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DeleteCallback;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.dialog.DeleteFragmentDialog;
import com.aps.apspda.dialog.WarnPop;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.EqpEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.InputDataEntity;
import com.aps.apspda.entity.LotInfoEntity;
import com.aps.apspda.entity.MaterialInfoBean;
import com.aps.apspda.entity.MessageEntity;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class StartFunctionActivity extends BaseActivity {

    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.etLotItem)
    EditText etLotItem;
    @BindView(R.id.etNum)
    EditText etNum;
    @BindView(R.id.tvLogId)
    TextView tvLogId;
    @BindView(R.id.tvDevice)
    TextView tvDevice;
    @BindView(R.id.tvWafer)
    TextView tvWafer;
    @BindView(R.id.tvRecipeName)
    TextView tvRecipeName;
    @BindView(R.id.tvRecipeNo)
    TextView tvRecipeNo;
    @BindView(R.id.rvThingList)
    RecyclerView rvThingList;
    @BindView(R.id.tvDeviceNo)
    TextView tvDeviceNo;
    @BindView(R.id.tvStatus)
    TextView tvStatus;
    @BindView(R.id.rvEqpList)
    RecyclerView rvEqpList;
    @BindView(R.id.ivRight)
    ImageView ivRight;
    @BindView(R.id.tvPic)
    TextView tvPic;
    @BindView(R.id.tvPicVersion)
    TextView tvPicVersion;
    @BindView(R.id.rlPic)
    RelativeLayout rlPic;
    @BindView(R.id.etRemark)
    EditText etRemark;
    @BindView(R.id.tvMore)
    TextView tvMore;
    @BindView(R.id.rvMessageList)
    RecyclerView rvMessageList;
    @BindView(R.id.ivDownArrow)
    ImageView ivDownArrow;
    @BindView(R.id.ivDownArrow2)
    ImageView ivDownArrow2;
    @BindView(R.id.rvInputList)
    RecyclerView rvInputList;
    @BindView(R.id.rlInfo)
    RelativeLayout rlInfo;
    @BindView(R.id.tvSubmitRemark)
    TextView tvSubmitRemark;
    @BindView(R.id.toggleButton)
    ToggleButton toggleButton;
    @BindView(R.id.llMain)
    LinearLayout llMain;


    private List<MessageEntity> messageEntityList;
    private Timer timer;
    private ThingListAdapter thingListAdapter;
    private EqpThingListAdapter eqpThingListAdapter;
    private MessageListAdapter messageListAdapter;
    private InputDataListAdapter inputDataListAdapter;
    private String LotID = "";
    private String startMode = "A";
    private Animation animation, animationDismiss;
    private List<InputDataEntity.InputObject> inputList;
    private List<WarnPop> dialogList = new ArrayList<>();

    private LotInfoEntity lotInfo;
    private String pic, picVersion;
    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            StartFunctionActivity.this.finish();
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 将返回值回调到callBack的参数中
            switch (msg.what) {
                case 0:
                    requestData();
                    break;
            }
        }
    };

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_start_function;
    }

    @Override
    protected void initView() {
        topView.setTitle("批次开始(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        topView.setTitleMode(TitleView.NORMAL_TEXT_MODE);
        topView.setLeftListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AntiShake.check(v.getId())) {    //判断是否多次点击
                    ToastUtils.showFreeToast("请勿重复点击",
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    return;
                }
                final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                deleteFragmentDialog.setData("确定返回主界面吗？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        deleteFragmentDialog.dismiss();
                        unbindLot();
                    }
                });
                deleteFragmentDialog.show(getSupportFragmentManager(), "unbind_dialog");
            }
        });

        rvInputList.setLayoutManager(new LinearLayoutManager(StartFunctionActivity.this));
        rvInputList.setItemAnimator(new DefaultItemAnimator());
        rvInputList.addItemDecoration(new DividerItemDecoration(StartFunctionActivity.this, 1));

        rvThingList.setLayoutManager(new LinearLayoutManager(StartFunctionActivity.this));
        rvThingList.setItemAnimator(new DefaultItemAnimator());
        rvThingList.addItemDecoration(new DividerItemDecoration(StartFunctionActivity.this, 1));

        rvEqpList.setLayoutManager(new LinearLayoutManager(StartFunctionActivity.this));
        rvEqpList.setItemAnimator(new DefaultItemAnimator());
        rvEqpList.addItemDecoration(new DividerItemDecoration(StartFunctionActivity.this, 1));

        rvMessageList.setLayoutManager(new LinearLayoutManager(StartFunctionActivity.this));
        rvMessageList.setItemAnimator(new DefaultItemAnimator());
        rvMessageList.addItemDecoration(new DividerItemDecoration(StartFunctionActivity.this, 1));
        etLotItem.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        etLotItem.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
                    if (s.length() > 0) {
                        LotID = s.toString();
                        requestLotInfo();
                    } else {
                        ToastUtils.showFreeToast("扫描信息有误", StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    startMode = "M";
                } else {
                    startMode = "A";
                }
            }
        });
    }

    @Override
    protected void initData() {
        etLotItem.postDelayed(new Runnable() {
            @Override
            public void run() {
                etLotItem.requestFocus();
            }
        }, 500);
        setCallback(etLotItem);
        messageEntityList = new ArrayList<>();
        messageListAdapter = new MessageListAdapter(messageEntityList);
        messageListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        messageListAdapter.isFirstOnly(true);
        rvMessageList.setAdapter(messageListAdapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        if (timer != null) {
            timer.cancel();
        }
        mHandler.removeCallbacks(runnable);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            boolean isAll = true;
            for (WarnPop warnPop : dialogList) {
                if (warnPop.isShowing()) {
                    isAll = false;
                    break;
                }
            }
            if (isAll) {
                final DeleteFragmentDialog deleteFragmentDialog = new DeleteFragmentDialog();
                deleteFragmentDialog.setData("确定返回主界面吗？", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        deleteFragmentDialog.dismiss();
                        unbindLot();
                    }
                });
                deleteFragmentDialog.show(getSupportFragmentManager(), "unbind_dialog");
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void unbindLot() {
        if (lotInfo != null) {
            if (lotInfo.getIsProcessStart()) {
                StartFunctionActivity.this.finish();
            } else {
                requestUnbind();
            }
        } else {
            StartFunctionActivity.this.finish();
        }
    }

    private void requestLotInfo() {
        EntityCallBack<BaseEntity<LotInfoEntity>> callBack = new DialogEntityCallBack<BaseEntity<LotInfoEntity>>
                (new TypeToken<BaseEntity<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LotInfoEntity>> response) {

                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    if (response.body().isNotNull()) {
                        setData(response.body().getData());
                    } else {
                        ToastUtils.showFreeToast("扫描的LOT信息不存在",
                                StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    }
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<LotInfoEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "LotIn");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("LOTID", LotID);
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/LotIn", map, callBack);
    }

    private void requestUnbind() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    ToastUtils.showFreeToast("解除绑定成功",
                            StartFunctionActivity.this, true, Toast.LENGTH_SHORT);
                    mHandler.postDelayed(runnable, 1000);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "RemoveEQPLot");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/RemoveEQPLot", map, callBack);
    }

    private void setData(LotInfoEntity lotInfoEntity) {
        lotInfo = lotInfoEntity;
        if (lotInfoEntity == null) {
            etLotItem.setEnabled(true);
            tvSubmitRemark.setVisibility(View.GONE);
            topView.setRightListener("", new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                }
            });
            lotInfoEntity = new LotInfoEntity();
        } else {
            tvSubmitRemark.setVisibility(View.VISIBLE);
            if (lotInfoEntity.getIsProcessStart()) {
                etLotItem.setEnabled(false);
                topView.setRightListener("结束作业", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        Intent intent = new Intent(StartFunctionActivity.this, EndFunctionActivity.class);
                        intent.putExtra("eqpID", getEqpID());
                        startActivityForResult(intent, 1);
                    }
                });
            } else {
                topView.setRightListener("开始作业", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (AntiShake.check(v.getId())) {    //判断是否多次点击
                            ToastUtils.showFreeToast("请勿重复点击",
                                    StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }
                        if (LotID.length() == 0) {
                            ToastUtils.showFreeToast("请先扫描LotID", StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                        } else {
                            if (lotInfo == null) {
                                ToastUtils.showFreeToast("获取Lot信息失败", StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                            } else {
                                boolean isOk = true;
                                for (InputDataEntity.InputObject inputObject : inputList) {
                                    if (inputObject.getISNULL().equalsIgnoreCase("Y")) {
                                        if (inputObject.getDATAVALUE().length() == 0) {
                                            isOk = false;
                                            ToastUtils.showFreeToast("请填写带*栏数据", StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                            break;
                                        }
                                    }
                                }
                                if (isOk) {
                                    requestStartWork();
                                }
                            }
                        }
                    }
                });
                etLotItem.setEnabled(true);
            }
        }
        LotID = lotInfoEntity.getLotId();

        thingListAdapter = new ThingListAdapter(lotInfoEntity.getMaterials().getMesMaterial());
        thingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        thingListAdapter.isFirstOnly(true);
        rvThingList.setAdapter(thingListAdapter);

        pic = lotInfoEntity.getDiagram();
        picVersion = lotInfoEntity.getDiagramVersion();
        rlPic.setVisibility(pic.length() > 0 && picVersion.length() > 0 ? View.VISIBLE : View.GONE);

        tvLogId.setText(lotInfoEntity.getLotId());
        tvDevice.setText(lotInfoEntity.getDevice());
        tvWafer.setText(lotInfoEntity.getWaferSource());
        tvRecipeName.setText(lotInfoEntity.getRecipeId());
        tvRecipeNo.setText(lotInfoEntity.getRecipeNo());
        tvPic.setText(lotInfoEntity.getDiagram());
        tvPicVersion.setText(lotInfoEntity.getDiagramVersion());
        etNum.setText(lotInfoEntity.getTotalQty());
    }

    private void requestStartWork() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    ToastUtils.showFreeToast("开始作业成功",
                            StartFunctionActivity.this, true, Toast.LENGTH_SHORT);
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "StartProcess");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EqpId", getEqpID());
        map.put("LotId", LotID);
        map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
        map.put("Remark", etRemark.getText().toString().trim());
        map.put("TotalQty", etNum.getText().toString().trim().length() == 0 ? "0" : etNum.getText().toString().trim());
        JSONObject jsonObject = new JSONObject();
        try {
            if (inputList.size() == 0) {
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(inputList));
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", jsonArray));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        map.put("StartMode", startMode);
        NetUtils.requestNet(this, "/StartProcess", map, callBack);
    }

    private void requestData() {
        EntityCallBack<BaseEntity<EqpEntity>> callBack = new DialogEntityCallBack<BaseEntity<EqpEntity>>
                (new TypeToken<BaseEntity<EqpEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<EqpEntity>> response) {
                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    EqpEntity eqpEntity = response.body().getData();
                    tvDeviceNo.setText(eqpEntity.getEQPID());
                    tvStatus.setText(eqpEntity.getCONTROLSTATUS());
                    if (eqpEntity.getMATERIALINFO().getMATERIALINFO().size() == 0) {
                        ToastUtils.showFreeToast("该设备没有设置BOM,请联系相关人员",
                                StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    }
                    inputList = eqpEntity.getINPUTDATALIST().getINPUTDATA();
                    inputDataListAdapter = new InputDataListAdapter(inputList);
                    inputDataListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    inputDataListAdapter.isFirstOnly(true);
                    rvInputList.setAdapter(inputDataListAdapter);

                    eqpThingListAdapter = new EqpThingListAdapter(eqpEntity.getMATERIALINFO().getMATERIALINFO(), new DeleteCallback() {
                        @Override
                        public void onSuccess(MaterialInfoBean bean) {
                            final EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                                    (new TypeToken<BaseEntity<FinishLotEntity>>() {
                                    }.getType(), getSupportFragmentManager(), this) {

                                @Override
                                public void onSuccess
                                        (final Response<BaseEntity<FinishLotEntity>> response) {
                                    if (response.body().isSuccess(StartFunctionActivity.this)) {
                                        ToastUtils.showFreeToast("删除物料成功",
                                                StartFunctionActivity.this, true, Toast.LENGTH_SHORT);
                                        requestData();
                                    } else {
                                        ToastUtils.showFreeToast(response.body().getMessage(),
                                                StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                    }
                                }

                                @Override
                                public void onError
                                        (Response<BaseEntity<FinishLotEntity>> response) {
                                    super.onError(response);
                                    loadError(response.getException(), "UnloadEQPMeterial");
                                }
                            };

                            Map<String, String> map = new HashMap<>();
                            map.put("EqpId", getEqpID());
                            map.put("MaterialPartNo", bean.getMaterialPartNo());
                            map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                            map.put("Type", bean.getType());
                            map.put("SeqNo", bean.getSeqNo());
                            NetUtils.requestNet(this, "/UnloadEQPMeterial", map, callBack);
                        }
                    });
                    eqpThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    eqpThingListAdapter.setFragmentManager(getSupportFragmentManager());
                    eqpThingListAdapter.isFirstOnly(true);
                    rvEqpList.setAdapter(eqpThingListAdapter);
                    setData(eqpEntity.getLOTINFO());
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                    mHandler.postDelayed(runnable, 1000);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<EqpEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowEQPInfoC2E");
                mHandler.postDelayed(runnable, 1000);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        NetUtils.requestNet(this, "/ShowEQPInfoC2E", map, callBack);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        AppUtils.saveErrorMessages("接收eid是：" + getEqpID(), "日志记录");
        requestData();
        startTimer();
    }

    private void requestMessageData() {
        EntityCallBack<BaseEntity<List<MessageEntity>>> callBack = new EntityCallBack<BaseEntity<List<MessageEntity>>>
                (new TypeToken<BaseEntity<List<MessageEntity>>>() {
                }.getType()) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<List<MessageEntity>>> response) {
                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    messageEntityList.clear();
                    messageEntityList.addAll(response.body().getData());
                    messageListAdapter.notifyDataSetChanged();
                    dealMessage(response.body().getData());
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<List<MessageEntity>>> response) {
                super.onError(response);
                AppUtils.saveErrorMessages(response.getException(), "SHOWMSG2PDA");
                ToastUtils.showFreeToast("获取实时消息失败",
                        StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", getEqpID());
        map.put("number", "5");
        NetUtils.requestNet(this, "/SHOWMSG2PDA", map, callBack);
    }

    private void dealMessage(List<MessageEntity> data) {
        dialogList.clear();
        for (int i = 0; i < data.size(); i++) {
            if (data.get(i).getISALERT()) {
                WarnPop warnPop = new WarnPop(this, data.get(i).getMESSAGE());
                dialogList.add(warnPop);
                if (timer != null) {
                    timer.cancel();
                }
            }
            if (data.get(i).getISEQPSTATUS()) {
                tvStatus.setText(data.get(i).getEQPSTATUS());
            }
        }
        for (int j = 0; j < dialogList.size(); j++) {
            final WarnPop warnPop = dialogList.get(j);
            try {
                warnPop.showAtLocation(llMain, Gravity.CENTER, 0, 0);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (j == 0) {
                warnPop.setOnlickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        warnPop.dismiss();
                        startTimer();
                    }
                });
            } else {
                warnPop.setOnlickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        warnPop.dismiss();
                    }
                });
            }
        }
        Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        vibrator.vibrate(1000 * dialogList.size());
    }

    private void startTimer() {
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                requestMessageData();
            }
        }, 0, 2000);
    }

    @OnClick({R.id.tvSubmitInput, R.id.rlMore, R.id.rlPic, R.id.rlInfo, R.id.tvSubmitRemark, R.id.rlInput})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.tvSubmitInput:
                boolean isInputOk = true;
                for (InputDataEntity.InputObject inputObject : inputList) {
                    inputObject.setEQPID(getEqpID());
                    if (isInputOk) {
                        if (inputObject.getISNULL().equalsIgnoreCase("Y")) {
                            if (inputObject.getDATAVALUE().length() == 0) {
                                ToastUtils.showFreeToast("请填写带*栏数据", StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                                isInputOk = false;
                            }
                        }
                    }
                }
                if (isInputOk) {
                    requestInputData();
                }
                break;
            case R.id.rlInfo:
                if (rvThingList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow.startAnimation(animationDismiss);
                    rvThingList.setVisibility(View.GONE);
                } else {
                    if (animation == null) {
                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setDuration(500);
                        animation.setFillAfter(true);
                    }
                    ivDownArrow.startAnimation(animation);
                    rvThingList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rlInput:
                if (rvInputList.getVisibility() == View.VISIBLE) {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animationDismiss);
                    rvInputList.setVisibility(View.GONE);
                } else {
                    if (animation == null) {
                        animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animation.setDuration(500);
                        animation.setFillAfter(true);
                    }
                    ivDownArrow2.startAnimation(animation);
                    rvInputList.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.rlMore:
                Intent allMessageIntent = new Intent(StartFunctionActivity.this, AllMessageActivity.class);
                allMessageIntent.putExtra("eqpID", getEqpID());
                startActivity(allMessageIntent);
                break;
            case R.id.rlPic:
                Intent intent = new Intent(StartFunctionActivity.this, PicViewActivity.class);
                intent.putExtra("pic", pic);
                intent.putExtra("picVersion", picVersion);
                startActivity(intent);
                break;
            case R.id.tvSubmitRemark:
                if (etRemark.getText().toString().trim().length() > 0) {
                    requestSubmitRemark(getEqpID(), LotID, etRemark.getText().toString(), StartFunctionActivity.this, getSupportFragmentManager());
                } else {
                    ToastUtils.showFreeToast("请填写备注后再提交",
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
                break;
        }
    }

    private void requestInputData() {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(StartFunctionActivity.this)) {
                    ToastUtils.showFreeToast("提交数据成功",
                            StartFunctionActivity.this, true, Toast.LENGTH_SHORT);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            StartFunctionActivity.this, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "SubmitInputData");
            }
        };

        Map<String, String> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        try {
            if (inputList.size() == 0) {
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", ""));
            } else {
                JSONArray jsonArray = new JSONArray(new Gson().toJson(inputList));
                jsonObject.put("InputDataList", new JSONObject().put("INPUTDATA", jsonArray));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put("InputDataList", jsonObject.toString());
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        NetUtils.requestNet(this, "/SubmitInputData", map, callBack);
    }

    public static void requestSubmitRemark(String eid, String lotID, String remark, final Context context, FragmentManager fragmentManager) {
        EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                (new TypeToken<BaseEntity<FinishLotEntity>>() {
                }.getType(), fragmentManager, context) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<FinishLotEntity>> response) {
                if (response.body().isSuccess(context)) {
                    ToastUtils.showFreeToast("提交备注成功",
                            context, true, Toast.LENGTH_SHORT);
                } else {
                    ToastUtils.showFreeToast(response.body().getMessage(),
                            context, false, Toast.LENGTH_SHORT);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<FinishLotEntity>> response) {
                super.onError(response);
                AppUtils.saveErrorMessages(response.getException(), "SubmitRemakeC2E");
                ToastUtils.showFreeToast("连接服务器失败",
                        context, false, Toast.LENGTH_SHORT);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EQPID", eid);
        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
        map.put("LOTID", lotID);
        map.put("REMARK", remark);
        NetUtils.requestNet(context, "/SubmitRemakeC2E", map, callBack);
    }
}
